#include "EditorMeshPageModel.h"
#include "Window/EditorWindowGroupModel.h"

#include "Mesh/StaticMesh.h"
#include "Material/Material.h"

#include "Asset/AssetSubsystem.h"

TSharedObjectPtr<REditorPageModel> REditorMeshPageModel::ShareClone(RObject *InOwner) const
{
    TSharedObjectPtr<REditorMeshPageModel> NewModel = NewObject<REditorMeshPageModel>(InOwner);
    NewModel->Mesh = Mesh;
    NewModel->FilePath = FilePath;
    return NewModel;
}

TSharedObjectPtr<RObject> REditorMeshPageModel::GetFocuseObject() const
{
    return Mesh;
}

TSharedObjectPtr<REditorMeshPageModel> REditorMeshPageModel::Create(const SPath &InPath, TSharedObjectPtr<RStaticMesh> InMesh)
{
    TSharedObjectPtr<REditorMeshPageModel> NewPageModel = NewObject<REditorMeshPageModel>(REditorWindowGroupModel::Get());
    NewPageModel->Mesh = InMesh;
    NewPageModel->FilePath = InPath;
    return NewPageModel;
}

TSharedObjectPtr<RStaticMesh> REditorMeshPageModel::GetMesh() const
{
    return Mesh;
}

void REditorMeshPageModel::SetMaterial(int64_t MaterialSlotIndex, TSharedObjectPtr<RMaterial> InMaterial)
{
    auto Operation = NewObject<REditorPageOperation>();
    REditorPageOperationWeakPtr OperationWeakPtr = Operation;
    Operation->Objects.Add(InMaterial);
    Operation->Objects.Add(Mesh->DefaultMaterials[MaterialSlotIndex]);
    Operation->RedoFunction.Bind([MaterialSlotIndex,OperationWeakPtr](TSharedObjectPtr<REditorMeshPageModel> MeshPageModel)
    {
        MeshPageModel->Mesh->DefaultMaterials[MaterialSlotIndex]=OperationWeakPtr ->Objects[0];
    });
    Operation->UndoFunction.Bind([MaterialSlotIndex,OperationWeakPtr](TSharedObjectPtr<REditorMeshPageModel> MeshPageModel)
    {
        MeshPageModel->Mesh->DefaultMaterials[MaterialSlotIndex]=OperationWeakPtr ->Objects[1];
    });

    AddAndRedoOperation(Operation);
}

void REditorMeshPageModel::LowLevelSave()
{
    RAssetSubsystem::Get()->ResaveLoadedAsset(
        Mesh
        ,nullptr
        ,nullptr);
}
